﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace HobSoft.SoccerBet2014.Domain.Common.BfApi
{
    public abstract class ApiRpcClient
    {
        protected abstract string EndPoint { get; }
        protected HttpClient RequestClient;

        public ApiRpcClient(string key, string token)
        {
            RequestClient = new HttpClient();
            RequestClient.DefaultRequestHeaders.Add("X-Application", key);
            RequestClient.DefaultRequestHeaders.Add("X-Authentication", token);
            RequestClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json-rpc"));
            RequestClient.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("UTF-8"));
        }

        public async virtual Task<JObject> PostAsync(string method, ApiJsonRpcContent content)
        {
            var response = await RequestClient.PostAsync(EndPoint, content);
            response.EnsureSuccessStatusCode();
            var result = await response.Content.ReadAsStringAsync();
            var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(result);
            if (apiResponse.HasError)
                ThrowException(apiResponse.Error);
            return apiResponse.Result;
        }

        protected virtual void ThrowException(ApiError error)
        {
            var data = error.Data;
            var exceptionName = data.Property("exceptionname").Value.ToString();
            var exceptionData = data.Property(exceptionName).Value.ToString();
            var exception = JsonConvert.DeserializeObject<APINGException>(exceptionData);
            throw exception;
        }
    }
}
